/*
 * @Author: szx
 * @Date: 2023-04-17 14:28:21
 * @LastEditTime: 2023-04-17 16:44:01
 * @Description: 
 * @FilePath: \learn\fullstackopen\part6\redux-anecdotes-main\src\reducers\notificationReducer.js
 */
import { createSlice } from '@reduxjs/toolkit'
const notificationSlice = createSlice({
    name: 'notification',
    initialState: '',
    reducers: {
        showNotification: (state, action) => {
            const content = action.payload;
            return content;
        },
        clearNotification: (state, action) => {
            return '';
        },
    }
})

const { showNotification, clearNotification } = notificationSlice.actions

let timeout = null;
export const setNotification = (msg, time) => {
    return async dispatch => {
        dispatch(showNotification(msg))
        if (timeout) {
            clearTimeout(timeout)
        }
        timeout = setTimeout(() => {
            dispatch(clearNotification())
            clearTimeout(timeout)
            timeout = null
        }, time * 1000)
    }

}
export default notificationSlice.reducer